<template>
  <view class="asset-page" :style="cssVars">
    <z-paging ref="paging" v-model="dataList" @query="queryList">
      <template #top>
        <!-- 搜索框 + 扫码按钮 -->
        <view class="search-bar">
          <up-search
            v-model="search"
            :placeholder="searchPlaceholder"
            shape="square"
            clearable
            :show-action="false"
            @search="handleConfirm"
            @change="handleConfirm"
          />
          <view class="scan-btn" @click="onScan">
            <up-icon name="scan" size="55rpx" color="#333" />
          </view>
        </view>
        <up-tabs
          :list="tabList"
          :current="tabIndex"
          @change="tabsChange"
          lineColor="#2979ff"
          itemStyle="background:#fff;height: 80rpx;width: 100%;border-bottom: 1rpx solid #f5f5f5;"
        />
        <!-- 资产列表筛选 -->
        <template v-if="tabIndex === 0">
          <!-- 筛选栏 -->
          <view class="filter-bar">
            <up-dropdown ref="uDropdownRef">
              <up-dropdown-item
                :title="assetList.state.text || '资产状态'"
                :options="filter.assetStatus"
              >
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true" style="height: 500rpx">
                    <view
                      v-for="item in filter.assetStatus"
                      :key="item.id"
                      class="assets-class"
                      @click="handleFilterClick(item, 'state')"
                      >{{ item.text }}</view
                    >
                  </scroll-view>
                  <up-button type="primary" @click="assetsClassclose('state')"
                    >清空</up-button
                  >
                </view>
              </up-dropdown-item>
              <up-dropdown-item
                :title="assetList.class.asset_class_name || '资产分类'"
              >
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true" style="height: 500rpx">
                    <view
                      v-for="item in filter.assetClass"
                      :key="item.id"
                      class="assets-class"
                      @click="handleFilterClick(item, 'class')"
                      >{{ item.asset_class_name }}</view
                    >
                  </scroll-view>
                  <up-button type="primary" @click="assetsClassclose('class')"
                    >清空</up-button
                  >
                </view>
              </up-dropdown-item>
              <up-dropdown-item title="标签">
                <view
                  class="slot-content"
                  style="background-color: #ffffff; padding-top: 25rpx"
                >
                  <scroll-view scroll-y="true" style="height: 100rpx">
                    <up-input
                      v-model="assetList.label_number"
                      placeholder="请输入标签"
                      border="surround"
                    />
                  </scroll-view>
                  <view style="display: flex">
                    <up-button type="primary" @click="labelNumberclose()"
                      >确定</up-button
                    >
                    <up-button
                      type="primary"
                      @click="assetsClassclose('label_number')"
                      >清空</up-button
                    >
                  </view>
                </view>
              </up-dropdown-item>
            </up-dropdown>
          </view>

          <!-- 总览信息 -->
          <view class="overview">
            <text>资产数量: {{ assetCount }}</text>
            <text>资产金额: {{ assetAmount }}</text>
          </view>
        </template>
        <!-- 资产领用筛选 -->
        <template v-if="tabIndex === 1">
          <view class="filter-bar">
            <up-dropdown ref="uDropdownRef">
              <up-dropdown-item
                :title="assetRequisitionList.approval_state.text || '审核状态'"
              >
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true" style="height: 420rpx">
                    <view
                      v-for="item in filter.disposalStatus"
                      :key="item.id"
                      class="assets-class"
                      @click="handleAssetrequisitionClick(item, 'state')"
                      >{{ item.text }}</view
                    >
                  </scroll-view>
                  <up-button
                    type="primary"
                    @click="handleAssetrequisitionClose('state')"
                    >清空</up-button
                  >
                </view>
              </up-dropdown-item>
              <up-dropdown-item title="更多筛选">
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true">
                    <view class="more-container">
                      <view class="more-container-items">
                        <up-input
                          v-model="assetRequisitionList.asset_code"
                          placeholder="请输入资产编码"
                          :customStyle="{ marginRight: '20rpx' }"
                          clearable
                        />
                        <up-input
                          v-model="assetRequisitionList.user.text"
                          placeholder="请选择领用人"
                          @click="handleAssetRequisitionUser"
                          clearable
                        />
                      </view>
                      <view class="more-container-items">
                        <up-input
                          v-model="assetRequisitionList.borrow_date"
                          placeholder="请选择领用日期"
                          :customStyle="{ marginRight: '20rpx' }"
                          @click="assetRequisitionList.showPicker = true"
                          clearable
                        />
                        <up-input
                          v-model="assetRequisitionList.asset_name"
                          placeholder="请输入资产名称"
                          clearable
                        />
                      </view>
                      <view class="more-container-items">
                        <up-input
                          v-model="assetRequisitionList.label_number"
                          placeholder="请输入标签编码"
                          :customStyle="{ marginRight: '20rpx' }"
                          clearable
                        />
                        <up-input
                          v-model="assetRequisitionList.borrow_state.text"
                          placeholder="请选择领用状态"
                          @click="handleUsageStatus"
                          clearable
                        />
                      </view>
                      <view class="more-container-items">
                        <up-input
                          v-model="assetRequisitionList.borrow_name"
                          placeholder="请输入领用单名称"
                          clearable
                        />
                      </view>
                    </view>
                  </scroll-view>
                  <view style="display: flex">
                    <up-button
                      type="primary"
                      @click="handleAssetRequisitionConfirm"
                      >确定</up-button
                    >
                    <up-button
                      type="primary"
                      @click="handleAssetRequisitionClear"
                      >清空</up-button
                    >
                  </view>
                </view>
              </up-dropdown-item>
            </up-dropdown>
          </view>
        </template>
        <template v-if="tabIndex === 2">
          <view class="filter-bar">
            <up-dropdown ref="returnDropdownRef">
              <up-dropdown-item
                :title="assetReturnList.approval_state.text || '审核状态'"
              >
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true" style="height: 420rpx">
                    <view
                      v-for="item in filter.disposalStatus"
                      :key="item.id"
                      class="assets-class"
                      @click="handleAssetReturnClick(item, 'state')"
                      >{{ item.text }}</view
                    >
                  </scroll-view>
                  <up-button
                    type="primary"
                    @click="handleAssetReturnClose('state')"
                    >清空</up-button
                  >
                </view>
              </up-dropdown-item>
              <up-dropdown-item title="更多筛选">
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true">
                    <view class="more-container">
                      <view class="more-container-items">
                        <up-input
                          v-model="assetReturnList.user.text"
                          placeholder="请选择退库人"
                          @click="handleAssetReturnUser"
                          clearable
                          style="width: 100%"
                        />
                      </view>
                      <view class="more-container-items">
                        <up-input
                          v-model="assetReturnList.dateRange"
                          placeholder="请选择退库日期"
                          style="width: 100%"
                          @click="assetReturnList.showPicker = true"
                          clearable
                        />
                      </view>
                      <view class="more-container-items">
                        <up-input
                          v-model="assetReturnList.return_name"
                          placeholder="请输入退库单名称"
                          style="width: 100%"
                          clearable
                        />
                      </view>
                    </view>
                  </scroll-view>
                  <view style="display: flex">
                    <up-button type="primary" @click="handleAssetReturnQuery()"
                      >确定</up-button
                    >
                    <up-button type="primary" @click="handleAssetReturnClear"
                      >清空</up-button
                    >
                  </view>
                </view>
              </up-dropdown-item>
            </up-dropdown>
          </view>
        </template>
        <template v-if="tabIndex === 3">
  <view class="filter-bar">
    <up-dropdown ref="transferDropdownRef">
      <up-dropdown-item
        :title="assetTransferList.approval_state.text || '审核状态'"
      >
        <view class="slot-content" style="background-color: #ffffff">
          <scroll-view scroll-y="true" style="height: 420rpx">
            <view
              v-for="item in filter.disposalStatus"
              :key="item.id"
              class="assets-class"
              @click="handleAssetTransferClick(item, 'state')"
              >{{ item.text }}</view
            >
          </scroll-view>
          <up-button
            type="primary"
            @click="handleAssetTransferClose('state')"
            >清空</up-button
          >
        </view>
      </up-dropdown-item>
      <up-dropdown-item title="更多筛选">
        <view class="slot-content" style="background-color: #ffffff">
          <scroll-view scroll-y="true">
            <view class="more-container">
              <view class="more-container-items">
                <up-input
                  v-model="assetTransferList.user.text"
                  placeholder="请选择转移人"
                  @click="handleAssetTransferUser"
                  clearable
                  style="width: 100%"
                />
              </view>
              <view class="more-container-items">
                <up-input
                  v-model="assetTransferList.receiver_user.text"
                  placeholder="请选择接收人"
                  @click="handleAssetTransferReceiveUser"
                  clearable
                  style="width: 100%"
                />
              </view>
              <view class="more-container-items">
                <up-input
                  v-model="assetTransferList.dateRange"
                  placeholder="请选择转移日期"
                  style="width: 100%"
                  @click="assetTransferList.showPicker = true"
                  clearable
                />
              </view>
              <view class="more-container-items">
                <up-input
                  v-model="assetTransferList.transfer_name"
                  placeholder="请输入转移单名称"
                  style="width: 100%"
                  clearable
                />
              </view>
              <view class="more-container-items">
                <up-input
                  v-model="assetTransferList.receiver_location.text"
                  placeholder="请选择接收位置"
                  @click="handleAssetTransferLocation"
                  clearable
                  style="width: 100%"
                />
              </view>
            </view>
          </scroll-view>
          <view style="display: flex">
            <up-button type="primary" @click="handleAssetTransferQuery()"
              >确定</up-button
            >
            <up-button type="primary" @click="handleAssetTransferClear"
              >清空</up-button
            >
          </view>
        </view>
      </up-dropdown-item>
    </up-dropdown>
  </view>
</template>
		<template v-if="tabIndex === 4">
          <view class="filter-bar">
            <up-dropdown ref="warrantyDropdownRef">
              <up-dropdown-item
                :title="assetWarrantyList.repair_state.text || '报修状态'"
              >
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true" style="height: 420rpx">
                    <view
                      v-for="item in filter.repairStatus"
                      :key="item.id"
                      class="assets-class"
                      @click="handleAssetWarrantyClick(item, 'state')"
                      >{{ item.text }}</view
                    >
                  </scroll-view>
                  <up-button
                    type="primary"
                    @click="handleAssetWarrantyClose('state')"
                    >清空</up-button
                  >
                </view>
              </up-dropdown-item>
              <up-dropdown-item title="更多筛选">
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true">
                    <view class="more-container">
                      <view class="more-container-items">
                        <up-input
                          v-model="assetWarrantyList.user.text"
                          placeholder="请选择报修人"
                          @click="handleAssetWarrantyUser"
                          clearable
                          style="width: 100%"
                        />
                      </view>
                      <view class="more-container-items">
                        <up-input
                          v-model="assetWarrantyList.repair_code"
                          placeholder="请输入报修单号"
                          style="width: 100%"
                          clearable
                        />
                      </view>
                      <view class="more-container-items">
                        <up-input
                          v-model="assetWarrantyList.repair_name"
                          placeholder="请输入报修单名称"
                          style="width: 100%"
                          clearable
                        />
                      </view>
                    </view>
                  </scroll-view>
                  <view style="display: flex">
                    <up-button type="primary" @click="handleAssetWarrantyQuery()"
                      >确定</up-button
                    >
                    <up-button type="primary" @click="handleAssetWarrantyClear"
                      >清空</up-button
                    >
                  </view>
                </view>
              </up-dropdown-item>
            </up-dropdown>
          </view>
        </template>
		<template v-if="tabIndex === 5">
          <!-- 资产报废筛选栏 -->
          <view class="filter-bar">
            <up-dropdown ref="scrappingDropdownRef">
              <up-dropdown-item
                :title="scrappingFilter.state.text || '审核状态'"
              >
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true" style="height: 500rpx">
                    <view
                      v-for="item in filter.disposalStatus"
                      :key="item.id"
                      class="filter-item"
                      @click="handleScrappingStatusClick(item)"
                      >{{ item.state_name }}</view
                    >
                  </scroll-view>
                  <up-button type="primary" @click="clearScrappingStatus"
                    >清空</up-button
                  >
                </view>
              </up-dropdown-item>
              <up-dropdown-item
                :title="scrappingFilter.reason.text || '报废原因'"
              >
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true" style="height: 500rpx">
                    <view
                      v-for="item in filter.scrappingReasons"
                      :key="item.id"
                      class="filter-item"
                      @click="handleScrappingReasonClick(item)"
                      >{{ item.text }}</view
                    >
                  </scroll-view>
                  <up-button type="primary" @click="clearScrappingReason"
                    >清空</up-button
                  >
                </view>
              </up-dropdown-item>
              <up-dropdown-item
                :title="scrappingFilter.person.text || '报废人'"
              >
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true" style="height: 500rpx">
                    <view
                      v-for="item in filter.disposalUsers"
                      :key="item.id"
                      class="filter-item"
                      @click="handleScrappingPersonClick(item)"
                      >{{ item.text }}</view
                    >
                  </scroll-view>
                  <up-button type="primary" @click="clearScrappingPerson"
                    >清空</up-button
                  >
                </view>
              </up-dropdown-item>
            </up-dropdown>
          </view>
        </template>        <template v-if="tabIndex === 7">
          <!-- 资产处置筛选栏 -->
          <view class="filter-bar">
            <up-dropdown ref="disposalDropdownRef">
              <up-dropdown-item
                :title="disposalFilter.state.state_name || '审核状态'"
              >
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true" style="height: 500rpx">
                    <view
                      v-for="item in filter.disposalStatus"
                      :key="item.id"
                      class="filter-item"
                      @click="handleDisposalStatusClick(item)"
                      >{{ item.state_name }}</view
                    >
                  </scroll-view>
                  <up-button type="primary" @click="clearDisposalStatus"
                    >清空</up-button
                  >
                </view>
              </up-dropdown-item>
              <up-dropdown-item title="更多筛选">
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true">
                    <view class="more-container">
                      <!-- 处置类型 -->
                      <view class="more-container-items">
                        <up-input
                          v-model="disposalFilter.type.disposal_type_name"
                          placeholder="请选择处置类型"
                          @click="showDisposalTypeSelector"
                          clearable
                          style="width: 100%"
                        />
                      </view>
                      <!-- 处置日期 -->
                      <view class="more-container-items">
                        <up-input
                          v-model="disposalFilter.dateRange"
                          placeholder="请选择处置日期"
                          @click="disposalFilter.showPicker = true"
                          clearable
                          style="width: 100%"
                        />
                      </view>
                      <!-- 处置人 -->
                      <view class="more-container-items">
                        <up-input
                          v-model="disposalFilter.person.text"
                          placeholder="请选择处置人"
                          @click="showDisposalPersonSelector"
                          clearable
                          style="width: 100%"
                        />
                      </view>
                    </view>
                  </scroll-view>
                  <view style="display: flex">
                    <up-button type="primary" @click="handleDisposalQuery()"
                      >确定</up-button
                    >
                    <up-button type="primary" @click="clearAllDisposalFilters"
                      >清空</up-button
                    >
                  </view>
                </view>
              </up-dropdown-item>
            </up-dropdown>
          </view>
        </template>

        <template v-if="tabIndex === 8">
          <view class="filter-bar">
            <up-dropdown ref="uDropdownRef">
              <up-dropdown-item :title="assetChangeOrder.state.text || '状态'">
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true" style="height: 420rpx">
                    <view
                      v-for="item in filter.disposalStatus"
                      :key="item.id"
                      class="assets-class"
                      @click="handleAssetChangeOrderClick(item, 'state')"
                      >{{ item.text }}</view
                    >
                  </scroll-view>
                  <up-button
                    type="primary"
                    @click="handleAssetChangeOrderClose('state')"
                    >清空</up-button
                  >
                </view>
              </up-dropdown-item>
              <up-dropdown-item title="更多筛选">
                <view class="slot-content" style="background-color: #ffffff">
                  <scroll-view scroll-y="true">
                    <view class="more-container">
                      <view class="more-container-items">
                        <up-input
                          v-model="assetChangeOrder.change_date"
                          placeholder="请选择变更日期"
                          :customStyle="{ marginRight: '20rpx' }"
                          @click="assetChangeOrder.showPicker = true"
                          clearable
                        />
                        <up-input
                          v-model="assetChangeOrder.asset_name"
                          placeholder="请输入资产名称"
                          clearable
                        />
                      </view>
                      <view class="more-container-items">
                        <up-input
                          v-model="assetChangeOrder.change_reason"
                          placeholder="请输入变更原因"
                          :customStyle="{ marginRight: '20rpx' }"
                          clearable
                        />
                        <up-input
                          v-model="assetChangeOrder.asset_name"
                          placeholder="请输入资产名称"
                          clearable
                        />
                      </view>
                      <view class="more-container-items">
                        <up-input
                          v-model="assetChangeOrder.change_name"
                          placeholder="请输入变更单名称"
                          clearable
                        />
                      </view>
                    </view>
                  </scroll-view>
                  <view style="display: flex">
                    <up-button
                      type="primary"
                      @click="handleAssetChangeOrderConfirm"
                      >确定</up-button
                    >
                    <up-button
                      type="primary"
                      @click="handleAssetChangeOrderClear"
                      >清空</up-button
                    >
                  </view>
                </view>
              </up-dropdown-item>
            </up-dropdown>
          </view>
        </template>
      </template>
      <assetsList :dataList="dataList" v-if="tabIndex === 0" />
      <assetReturn :returnList="dataList" v-if="tabIndex === 2" />
      <assetRequisition
        :dataList="dataList"
        v-if="tabIndex === 1"
        @updateData="handleUpdate"
      />
      <assetTransfer :transferList="dataList" v-if="tabIndex === 3" />
      <assetWarranty :dataList="dataList" v-if="tabIndex === 4" />
      <assetScrapping :scrappingList="dataList" v-if="tabIndex === 5" />
      <assetRepair
        :dataList="dataList"
        v-if="tabIndex === 6"
        @reload-data="reloadData"
      />
      <assetDisposal :disposalList="dataList" v-if="tabIndex === 7" />

      <assetChangeorder
        :dataList="dataList"
        v-if="tabIndex === 8"
        @updateData="handleUpdate"
      />
    </z-paging>
    <!-- 新增资产 -->
    <view class="footer-btn" v-show="tabIndex !== 6">
      <template v-for="(item, index) in tabList">
        <up-button
          :key="item.name"
          v-if="index === tabIndex && item.add !== ''"
          @click="handleToAdd(item)"
          type="primary"
          :text="item.add"
        />
      </template>
    </view>
  </view>

  <!-- 领用选人 -->
  <up-picker
    :show="assetRequisitionList.show"
    :columns="assetRequisitionList.columns"
    keyName="text"
    @cancel="assetRequisitionList.show = false"
    @confirm="assetRequisitionConfirm"
    :closeOnClickOverlay="false"
  />

  <!-- 领用状态 -->
  <up-picker
    :show="assetRequisitionList.usageStatus"
    :columns="filter.usageStatus"
    keyName="text"
    @cancel="assetRequisitionList.usageStatus = false"
    @confirm="usageStatusConfirm"
    :closeOnClickOverlay="false"
  />

  <!-- 退库状态 -->
  <up-picker
    :show="assetReturnList.returnStatus"
    :columns="filter.usageStatus"
    keyName="text"
    @cancel="assetReturnList.returnStatus = false"
    @confirm="returnStatusConfirm"
    :closeOnClickOverlay="false"
  />

  <!-- 报修状态 -->
  <up-picker
    :show="assetWarrantyList.repairStatus"
    :columns="filter.usageStatus"
    keyName="text"
    @cancel="assetWarrantyList.repairStatus = false"
    @confirm="warrantyStatusConfirm"
    :closeOnClickOverlay="false"
  />

	<!-- 选报修人 -->
	<up-picker
	  :show="assetWarrantyList.show"
	  :columns="assetWarrantyList.columns"
	  keyName="text"
	  @cancel="assetWarrantyList.show = false"
	  @confirm="assetWarrantyConfirm"
	  :closeOnClickOverlay="false"
	/>

  <!-- 退库人选择 -->
  <up-picker
    :show="assetReturnList.show"
    :columns="assetReturnList.columns"
    keyName="text"
    @cancel="assetReturnList.show = false"
    @confirm="assetReturnConfirm"
    :closeOnClickOverlay="false"
  />

  <!-- 处置类型选择 -->
  <up-picker
    :show="disposalTypeShow"
    :columns="[filter.disposalTypes]"
    keyName="disposal_type_name"
    @cancel="disposalTypeShow = false"
    @confirm="confirmDisposalType"
    :closeOnClickOverlay="false"
  />

  <!-- 处置人选择 -->
  <up-picker
    :show="disposalPersonShow"
    :columns="[filter.disposalUsers]"
    keyName="text"
    @cancel="disposalPersonShow = false"
    @confirm="confirmDisposalPerson"
    :closeOnClickOverlay="false"
  />

  <!-- 时间范围选择弹窗 -->
  <TimeRangePicker
    v-model:pickerVisible="assetRequisitionList.showPicker"
    @update:start="handleStartTime"
    @update:end="handleEndTime"
  />

  <!-- 处置时间范围选择弹窗 -->
  <TimeRangePicker
    v-model:pickerVisible="disposalFilter.showPicker"
    mode="date"
    @update:start="handleDisposalStartTime"
    @update:end="handleDisposalEndTime"
  />

  <!-- 退库时间范围选择弹窗 -->
  <TimeRangePicker
    v-model:pickerVisible="assetReturnList.showPicker"
    mode="date"
    @update:start="handleReturnStartTime"
    @update:end="handleReturnEndTime"
  />

  <!-- 时间范围选择弹窗 -->
  <TimeRangePicker
    v-model:pickerVisible="assetChangeOrder.showPicker"
    @update:start="handleOrderStartTime"
    @update:end="handleOrderEndTime"
  />

<!-- 转移人选择 -->
<up-picker
  :show="assetTransferList.show"
  :columns="assetTransferList.columns"
  keyName="text"
  @cancel="assetTransferList.show = false"
  @confirm="assetTransferConfirm"
  :closeOnClickOverlay="false"
/>

<!-- 接收人选择 -->
<up-picker
  :show="assetTransferList.receiveUserShow"
  :columns="assetTransferList.columns"
  keyName="text"
  @cancel="assetTransferList.receiveUserShow = false"
  @confirm="assetTransferReceiveUserConfirm"
  :closeOnClickOverlay="false"
/>

<!-- 转移时间范围选择弹窗 -->
<TimeRangePicker
  v-model:pickerVisible="assetTransferList.showPicker"
  mode="date"
  @update:start="handleTransferStartTime"
  @update:end="handleTransferEndTime"
/>
<!-- 接收位置选择 -->
<up-picker
  :show="assetTransferList.locationShow"
  :columns="assetTransferList.locationColumns"
  keyName="text"
  @cancel="assetTransferList.locationShow = false"
  @confirm="assetTransferLocationConfirm"
  :closeOnClickOverlay="false"
/>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted,computed } from "vue";
import { debounce } from "lodash-es";
import http from "@/api/request";
import assetsList from "@/components/assetsList";
import { onShow, onLoad } from "@dcloudio/uni-app";
import { generateUUID, formatTimestamp } from "@/utils";
import assetDisposal from "@/components/assetDisposal";
import assetRepair from "@/components/assetRepair";
import assetReturn from "@/components/assetReturn";
import TimeRangePicker from "@/components/TimeRangePicker";
import assetRequisition from "@/components/assetRequisition";
import assetScrapping from "@/components/assetScrapping";
import assetChangeorder from "../assetChangeorder";
import assetWarranty from "@/components/assetWarranty";
import assetTransfer from "@/components/assetTransfer";

const search = ref("");
const paging = ref(null);

const tabList = ref([
  {
    name: "资产列表",
    add: "+ 新增资产",
    url: "/pages/assetsPages/info?name=add",
  },
  {
    name: "资产领用",
    add: "+ 新增领用",
    url: "/pages/assetRequisition/index?name=add",
  },
  { name: "资产退库", add: "+ 新增退库", url: "/pages/assetReturn/add" },
  { name: "资产转移", add: "+ 新增转移", url: "/pages/assetTransfer/add" },
  {
    name: "资产报修",
    add: "+ 新增报修",
    url: "/pages/assetWarranty/info?type=add",
  },
  { name: "资产报废", add: "+ 新增报废", url: "/pages/assetScrapping/add" },
  { name: "资产维修", add: "", url: "" },
  { name: "资产处置", add: "+ 新增处置单", url: "/pages/assetsDisposal/add" },
  {
    name: "资产变更",
    add: "+ 变更单",
    url: "/pages/assetChangeorder/info?name=add",
  },
]);

const searchPlaceholder = ref("搜索资产名称/编码");

const assetCount = ref(0);
const assetAmount = ref(0);
const dataList = ref([]);
const tabIndex = ref(0);
const uDropdownRef = ref(null);
const disposalDropdownRef = ref(null);
const returnDropdownRef = ref(null);
const warrantyDropdownRef = ref(null);
const disposalFilter = reactive({
  state: {},
  type: {},
  dateRange: "",
  startDate: "",
  endDate: "",
  person: {},
  personInput: "",
  showPicker: false,
});

const scrappingDropdownRef = ref(null);
const scrappingFilter = reactive({
  state: {},
  scrapping_name: "",
  reason: {},
  person: {},
});

const enumList = [
  { code: "getViewTable", name: "getAssetClassList", tabs: [0] },
  { code: "getBasicData", name: "asset>status", tabs: [0] },
  { code: "getBasicData", name: "asset>repair_status", tabs: [4] }, 
	{
    code: "getBasicData",
    name: "common>approve_status",
    tabs: [1, 2,3, 5, 7, 8],
  }, // 添加审核状态枚举
  {
    code: "getViewTable",
    name: "getAssetDisposalOrderAssetTypeList",
    tabs: [7],
  }, // 添加处置类型枚举
  { code: "getViewTable", name: "Sys_GetUserNameById", tabs: [1, 2,3, 4, 5, 7] }, // 添加处置类型枚举
  { code: "getBasicData", name: "asset>use_status", tabs: [1, 2] },
  { code: "getBasicData", name: "base>scrap_reason", tabs: [5] }, // 添加报废原因枚举
  { code: "getViewTable", name: "getAssetAddressList", tabs: [3] }, // 添加转移接收位置枚举
];

// 筛选枚举集合
const filter = reactive({
  assetClass: [],
  assetStatus: [],
  disposalStatus: [],
  disposalTypes: [],
  disposalUsers: [],
  usageStatus: [],
  scrappingReasons: [],
});

// 资产列表请求参数
const assetList = reactive({
  class: {},
  state: {},
  label_number: "",
  name: "",
});

const assetRequisitionList = reactive({
  approval_state: {},
  borrow_code: "",
  user: {},
  borrow_date: "",
  asset_name: "",
  borrow_name: "",
  label_number: "",
  borrow_state: {},
  show: false,
  columns: [], // 领用选人枚举
  start_date: "",
  end_date: "",
  showPicker: false,

  usageStatus: false,
});

// 变更单
const assetChangeOrder = reactive({
  state: {},
  change_date: "",
  start: "",
  end: "",
  asset_name: "",
  change_reason: "",
  asset_name: "",
  change_name: "",
  showPicker: false,
});

const assetReturnList = reactive({
  approval_state: {},
  return_code: "",
  user: {},
  return_date: "",
  return_name: "",
  asset_code: "",
  show: false,
  columns: [], // 退库选人枚举
  start_date: "",
  end_date: "",
  dateRange: "",
  showPicker: false,
  returnStatus: false,
});

const assetWarrantyList = reactive({
  repair_state: {},
  repair_name: "",
  user: {},
  repair_code: "",
  show: false,
  columns: [], // 报修选人枚举
  showPicker: false,
  repairStatus: false,
});

// 在reactive数据结构部分添加资产转移列表数据结构
const transferDropdownRef = ref(null);
const assetTransferList = reactive({
  approval_state: {},
  transfer_code: "",
  receiver_location:{
    text: "",
    id: ""
  },
  locationShow: false,
  locationColumns: [], // 接收位置选择枚举
  user: {},
  transfer_date: "",
  transfer_name: "",
  receiver_user: {},
  start_date: "",
  end_date: "",
  dateRange: "",
  show: false,
  columns: [], // 转移人选择枚举
  receiveUserShow: false,
  showPicker: false,
});

onShow(async () => {
  await getList();
});

onLoad(async (query) => {
  if (query.tabs) {
    tabIndex.value = Number(query.tabs);
  }
	// 待办跳转过来的初始化查询条件
	// 1 待审核，显示资产领用列表（待审核应该是包含多个列表），过滤条件待审核
	if (query.statusObj && '1' == query.tabs) {
		assetRequisitionList.approval_state = JSON.parse(query.statusObj);
		if (paging.value) {
		  paging.value.reload();
		}
	}
	// 2 待签收，显示资产退库列表（待签收应该是包含多个列表），过滤条件待签收
	if (query.statusObj && '2' == query.tabs) {
		assetReturnList.approval_state = JSON.parse(query.statusObj);
		if (paging.value) {
		  paging.value.reload();
		}
	}
});

const getList = async () => {
  if (paging.value) {
    paging.value.reload();
  }
  // 资产列表请求所有数据
  if (tabIndex.value === 0) {
    assetsAmount();
  }
  await getFilterList();
};

// 搜索函数
const handleConfirm = debounce(async () => {
  if (paging.value) {
    paging.value.reload();
  }
  // 资产列表获取数量、金额
  if (tabIndex.value === 0) {
    assetsAmount();
  }
}, 1000);

const onScan = () => {
  uni.scanCode({
    success: async (res) => {
      search.value = res.result;
      uni.showToast({ title: "扫码成功", icon: "success" });
    },
  });
};

// 获取资产列表
const getFilterList = async () => {
  const batchRequests = enumList
    .map((item) => {
      if (!item.tabs.includes(tabIndex.value)) return null;
      const params = [
        {
          id: generateUUID(),
          service: "Module",
          method: item.code,
          param: JSON.stringify({ code: item.name, filters: [] }),
        },
      ];

      return http.post("/api/module/GetBatchResult", params).then((res) => ({
        ...res,
        name: item.name,
      }));
    })
    .filter(Boolean);

  try {
    const results = await Promise.all(batchRequests);

    results.forEach(({ name, result, isSuccess, code }) => {
      console.log(name, result, isSuccess, code);
      if (!isSuccess || !code) return;
      switch (name) {
        case "getAssetClassList":
          filter.assetClass = result[0].response.data.viewTable;
          break;
        case "getAssetAddressList":
          assetTransferList.locationColumns.push(result[0].response.data.viewTable.map(item=>({
            id: item.asset_address_code,
            text: item.asset_address_name,
          })));
          console.log(filter);
          break;
        case "common>approve_status":
          // 处理审核状态数据
          if (
            result[0].response &&
            result[0].response.data &&
            result[0].response.data.data
          ) {
            if (tabIndex.value === 5) {
              filter.disposalStatus = result[0].response.data.data
                .filter((item) => item.filter && item.filter.includes("D"))
                .map((item) => ({
                  id: item.id,
                  state_name: item.text,
                  value: item.value,
                }));
            } else {
              filter.disposalStatus = [1, 2, 3, 8].includes(tabIndex.value)
                ? result[0].response.data.data
                : result[0].response.data.data
                    .filter((item) => item.filter && item.filter.includes("C"))
                    .map((item) => ({
                      id: item.id,
                      state_name: item.text,
                      value: item.value,
                    }));
            }
          }
          break;
        case "asset>status":
          filter.assetStatus = result[0].response.data.data;
          break;
        case "asset>repair_status":
          filter.repairStatus = result[0].response.data.data;
          break;
        case "getAssetDisposalOrderAssetTypeList":
          // 处理处置类型数据
          filter.disposalTypes = result[0].response.data.viewTable;
          break;
        case "Sys_GetUserNameById":
          // 处理处置人数据
          if (
            result[0].response &&
            result[0].response.data &&
            result[0].response.data.viewTable
          ) {
            filter.disposalUsers = result[0].response.data.viewTable;
            assetRequisitionList.columns = [];
            if (tabIndex.value === 1) {
              assetRequisitionList.columns.push(filter.disposalUsers);
            }
            if (tabIndex.value === 2) {
              assetReturnList.columns.push(filter.disposalUsers);
            }
            if (tabIndex.value === 3) {
              assetTransferList.columns.push(filter.disposalUsers);
            }
            if (tabIndex.value === 4) {
              assetWarrantyList.columns.push(filter.disposalUsers);
            }
          }
          break;

        case "asset>use_status":
          filter.usageStatus = [];
          filter.usageStatus.push(result[0].response.data.data);
          break;
        case "base>scrap_reason":
          console.log(result[0].response.data.data);
          filter.scrappingReasons = result[0].response.data.data;
          break;
      }
    });
  } catch (error) {
    console.error("获取枚举失败:", error);
  }
};

// 资产列表获取总金额
const assetsAmount = () => {
  assetAmount.value = 0;
  const data = {
    code: "getAssetList",
    filters: [
      { name: "state", value: assetList.state?.value || "" },
      { name: "class", value: assetList.class?.asset_class_code || "" },
      { name: "label_number", value: assetList.label_number },
      { name: "name", value: search.value || "" },
    ],
    allColumnFilter: true,
  };
  http.post("/api/module/GetViewTable", data).then((res) => {
    if (res.code && res.isSuccess) {
      res.result.viewTable.forEach((item) => {
        if (item.purchase_price) {
          assetAmount.value += item.purchase_price; // 采购价格
        }
      });
    }
  });
};

const handleFilterClick = (item, name) => {
  if (name === "state") {
    assetList.state = item;
  } else if (name === "class") {
    assetList.class = item;
  }
  uDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
  assetsAmount();
};

const assetsClassclose = (name) => {
  if (name === "state") {
    assetList.state = {};
  } else if (name === "class") {
    assetList.class = {};
  } else if (name === "label_number") {
    assetList.label_number = "";
  }
  uDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
  assetsAmount();
};

const handleAssetrequisitionClick = (item, name) => {
  if (name === "state") {
    assetRequisitionList.approval_state = item;
  }
  uDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const handleAssetrequisitionClose = (name) => {
  if (name === "state") {
    assetRequisitionList.approval_state = {};
  }
  uDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const labelNumberclose = () => {
  uDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
  assetsAmount();
};

const handleDisposalStatusClick = (item) => {
  disposalFilter.state = item;
  disposalDropdownRef.value.close();
  paging.value.reload();
};

const clearDisposalStatus = () => {
  disposalFilter.state = {};
  disposalDropdownRef.value.close();
  paging.value.reload();
};

// 显示处置类型选择器
const disposalTypeShow = ref(false);
const disposalPersonShow = ref(false);

const showDisposalTypeSelector = () => {
  disposalTypeShow.value = true;
};

// 显示处置人选择器
const showDisposalPersonSelector = () => {
  disposalPersonShow.value = true;
};

// 处置查询
const handleDisposalQuery = () => {
  disposalDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理处置开始时间
const handleDisposalStartTime = (time) => {
  disposalFilter.startDate = formatTimestamp(time, "yyyy-MM-dd");
  if (disposalFilter.startDate && disposalFilter.endDate) {
    disposalFilter.dateRange = `${disposalFilter.startDate} ~ ${disposalFilter.endDate}`;
  }
};

// 处理处置结束时间
const handleDisposalEndTime = (time) => {
  disposalFilter.endDate = formatTimestamp(time, "yyyy-MM-dd");
  if (disposalFilter.startDate && disposalFilter.endDate) {
    disposalFilter.dateRange = `${disposalFilter.startDate} ~ ${disposalFilter.endDate}`;
  }
};

// 清空所有处置筛选条件
const clearAllDisposalFilters = () => {
  disposalFilter.state = {};
  disposalFilter.type = {};
  disposalFilter.dateRange = "";
  disposalFilter.startDate = "";
  disposalFilter.endDate = "";
  disposalFilter.person = {};
  disposalFilter.personInput = "";
  disposalDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const queryList = (pageNo, pageSize) => {
  uni.showLoading({
    title: "加载中...",
    mask: true,
  });
  let data;
  if (tabIndex.value === 0) {
    data = {
      code: "getAssetList",
      allColumnFilter: true,
      filters: [
        { name: "state", value: assetList.state?.value || "" },
        { name: "class", value: assetList.class?.asset_class_code || "" },
        { name: "label_number", value: assetList.label_number },
        { name: "name", value: search.value || "" },
      ],
      pageInput: { currentPage: pageNo, pageSize: pageSize },
      permissionKey: "",
    };
  }
  if (tabIndex.value === 2) {
    data = {
      code: "getAssetReturnList",
      allColumnFilter: true,
      filters: [
        // 审核状态
        {
          name: "return_state",
          value: assetReturnList.approval_state?.value || "",
        },
        // 退库单号
        { name: "return_code", value: search.value || "" },
        // 退库人
        { name: "return_user", value: assetReturnList.user?.id || "" },
        // 退库日期
        { name: "return_date", value: assetReturnList.return_date || "" },
        // 开始结束日期
        { name: "start_date", value: assetReturnList.start_date || "" },
        { name: "end_date", value: assetReturnList.end_date || "" },
        // 退库单名称
        { name: "return_name", value: assetReturnList.return_name || "" },
      ],
      pageInput: { currentPage: pageNo, pageSize: pageSize },
      permissionKey: "",
    };
  }
	
  if (tabIndex.value === 3) {
    data = {
      code: "getAssetTransferList",
      allColumnFilter: true,
      filters: [
        // 审核状态
        {
          name: "transfer_state",
          value: assetTransferList.approval_state?.value || "",
        },
        // 转移单号
        { name: "transfer_code", value: search.value || "" },
        // 转移人
        { name: "transfer_user", value: assetTransferList.user?.id || "" },
        // 接收人
        { name: "receiver_user", value: assetTransferList.receiver_user?.id || "" },
        // 开始结束日期
        { name: "start_date", value: assetTransferList.start_date || "" },
        { name: "end_date", value: assetTransferList.end_date || "" },
        // 转移单名称
        { name: "transfer_name", value: assetTransferList.transfer_name || "" },
        // 接收位置
        { name: "receiver_location", value: assetTransferList.receiver_location?.id || "" },
      ],
      pageInput: { currentPage: pageNo, pageSize: pageSize },
      permissionKey: "",
    };
  }

  if (tabIndex.value === 4) {
    data = {
      code: "getRepairList",
      allColumnFilter: true,
      filters: [
        // 报修状态
        {
          name: "repair_state",
          value: assetWarrantyList.repair_state?.value || "",
        },
        // 报修单号
        { name: "repair_code", value: search.value || "" },
        // 报修人
        { name: "repair_user", value: assetWarrantyList.user?.id || "" },
        // 报修名称
        { name: "repair_name", value: assetWarrantyList.repair_name || "" },
      ],
      pageInput: { currentPage: pageNo, pageSize: pageSize },
      permissionKey: "",
    };
  }

  if (tabIndex.value === 1) {
    data = {
      code: "getAssetBorrowList",
      allColumnFilter: true,
      filters: [
        // 审核状态
        {
          name: "approval_state",
          value: assetRequisitionList.approval_state?.value || "",
        },
        // 领用单号
        {
          name: "borrow_code",
          value: search.value || "",
        },
        // 领用人
        { name: "user", value: assetRequisitionList.user?.id || "" },
        // 领用日期
        { name: "borrow_date", value: assetRequisitionList.borrow_date || "" },
        // 开始结束日期
        { name: "start_date", value: assetRequisitionList.start_date || "" }, // 领用日期
        { name: "end_date", value: assetRequisitionList.end_date || "" },
        // 资产名称
        { name: "asset_name", value: assetRequisitionList.asset_name || "" },
        // 领用单名称
        { name: "borrow_name", value: assetRequisitionList.borrow_name || "" },
        // 资产编号
        { name: "asset_code", value: assetRequisitionList.asset_code || "" },
        // 标签编码
        {
          name: "label_number",
          value: assetRequisitionList.label_number || "",
        },
        // 领用状态
        {
          name: "borrow_state",
          value: assetRequisitionList.borrow_state?.value || "",
        },
        {
          name: "repair_code",
          value: search.value || "",
        },
      ],
      pageInput: { currentPage: pageNo, pageSize: pageSize },
      permissionKey: "",
    };
  }
  if (tabIndex.value === 5) {
    console.log(disposalFilter);
    data = {
      code: "getScrapList",
      allColumnFilter: true,
      filters: [
        // 报废单单号
        { name: "scrap_code", value: search.value || "" },
        // 报废审核状态
        { name: "scrap_status", value: scrappingFilter.state?.value || "" },
        // 报废原因
        { name: "scrap_reason", value: scrappingFilter.reason?.value || "" },
        // 报废人
        { name: "scrap_user", value: scrappingFilter.person?.id || "" },
      ],
      pageInput: { currentPage: pageNo, pageSize: pageSize },
      permissionKey: "",
    };
  }
  if (tabIndex.value === 6) {
    data = {
      code: "getRepairList",
      allColumnFilter: true,
      filters: [
        {
          name: "repair_states",
          value:
            "PENDING_REPAIR,REPAIRING,ALL_REPAIR,REPAIR_COMPLETED,COMPLETED",
        },
				// 维修单号
				{ name: "repair_code", value: search.value || "" },
      ],
      pageInput: { currentPage: pageNo, pageSize: pageSize },
      permissionKey: "",
    };
  }
  if (tabIndex.value === 7) {
    data = {
      code: "getAssetDisposalList",
      allColumnFilter: true,
      filters: [
        { name: "state", value: disposalFilter.state.value || "" },
        { name: "disposalType", value: disposalFilter.type.id || "" },
        { name: "start", value: disposalFilter.startDate || "" },
        { name: "end", value: disposalFilter.endDate || "" },
        { name: "disposal_user", value: disposalFilter.person.id || "" },
        { name: "name", value: search.value || "" },
      ],
      pageInput: { currentPage: pageNo, pageSize: pageSize },
      permissionKey: "",
    };
  }

  if (tabIndex.value === 8) {
    data = {
      code: "getAssetChangeOrderList",
      allColumnFilter: true,
      filters: [
        { name: "change_date", value: assetChangeOrder.change_date },
        { name: "start", value: assetChangeOrder.start },
        { name: "end", value: assetChangeOrder.end },
        { name: "state", value: assetChangeOrder.state.value },
        { name: "change_code", value: search.value },
        { name: "change_reason", value: assetChangeOrder.change_reason },
        { name: "asset_name", value: assetChangeOrder.asset_name },
        { name: "change_name", value: assetChangeOrder.change_name },
      ],
      pageInput: { currentPage: pageNo, pageSize: pageSize },
      permissionKey: "",
    };
  }

  http.post("/api/module/GetViewTable", data).then((res) => {
    if (res.code && res.isSuccess) {
      paging.value.complete(res.result.viewTable);
      if (tabIndex.value === 0) {
        assetCount.value = res.result.totalCount;
      }
      uni.hideLoading();
    } else {
      uni.showToast({ title: res.error, duration: 1500, icon: "error" });
      uni.hideLoading();
    }
  });
};

const reloadData = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

const tabsChange = async (value) => {
  tabIndex.value = value.index;
  paging.value.reload();
  switch (value.index) {
    case 0:
      searchPlaceholder.value = "搜索资产名称/编码";
      assetsAmount();
      break;
    case 1:
      searchPlaceholder.value = "搜索领用单编码";
      break;
    case 4:
      searchPlaceholder.value = "搜索报修单编码";
      break;
    case 2:
      searchPlaceholder.value = "搜索退库单编码";
      break;
    case 3:
      searchPlaceholder.value = "搜索转移单号";
      break;
    case 5:
      searchPlaceholder.value = "搜索报废单号/名称";
      break;
    case 6:
      searchPlaceholder.value = "搜索维修单";
			break;
    case 7:
      searchPlaceholder.value = "搜索资产编码";
      break;
    case 8:
      searchPlaceholder.value = "搜索变更单号";
      break;
  }
  await getFilterList();
};

const handleToAdd = (item) => {
  uni.navigateTo({
    url: item.url,
  });
};

// 在 onShow 函数下方添加 onMounted 和 onUnmounted 生命周期钩子
onMounted(() => {
  // 监听处置数据变更事件
  uni.$on("data-changed", handleDataChanged);
});

onUnmounted(() => {
  // 移除事件监听
  uni.$off("data-changed", handleDataChanged);
});

// 处理处置数据变更事件
const handleDataChanged = () => {
  paging.value.reload();
};

// 确认处置类型选择
const confirmDisposalType = (e) => {
  console.log(e);
  disposalFilter.type = e.value[0];
  disposalTypeShow.value = false;
  if (paging.value) {
    paging.value.reload();
  }
};

// 确认处置人选择
const confirmDisposalPerson = (e) => {
  console.log(e);
  disposalFilter.person = e.value[0];
  disposalPersonShow.value = false;
  if (paging.value) {
    paging.value.reload();
  }
};

const handleAssetRequisitionUser = () => {
  assetRequisitionList.show = true;
};
const assetRequisitionConfirm = (e) => {
  assetRequisitionList.user.text = e.value[0].text;
  assetRequisitionList.user.id = e.value[0].id;
  assetRequisitionList.show = false;
};
const handleUsageStatus = () => {
  assetRequisitionList.usageStatus = true;
};
const usageStatusConfirm = (e) => {
  assetRequisitionList.borrow_state.text = e.value[0].text;
  assetRequisitionList.borrow_state.value = e.value[0].value;
  assetRequisitionList.usageStatus = false;
};

const returnStatusConfirm = (e) => {
  assetReturnList.return_state.text = e.value[0].text;
  assetReturnList.return_state.value = e.value[0].value;
  assetReturnList.returnStatus = false;
};

const warrantyStatusConfirm = (e) => {
  assetWarrantyList.repair_state.text = e.value[0].text;
  assetWarrantyList.repair_state.value = e.value[0].value;
  assetWarrantyList.repairStatus = false;
};

const handleStartTime = (e) => {
  assetRequisitionList.start_date = formatTimestamp(e);
};

const handleEndTime = (e) => {
  assetRequisitionList.end_date = formatTimestamp(e);

  assetRequisitionList.borrow_date = `${assetRequisitionList.start_date}-${assetRequisitionList.end_date}`;
};

const handleAssetRequisitionClear = () => {
  assetRequisitionList.borrow_state = {};
  assetRequisitionList.label_number = "";
  assetRequisitionList.asset_code = "";
  assetRequisitionList.borrow_name = "";
  assetRequisitionList.asset_name = "";
  assetRequisitionList.borrow_code = "";
  assetRequisitionList.user = {};
  assetRequisitionList.borrow_date = "";
  assetRequisitionList.start_date = "";
  assetRequisitionList.end_date = "";
  uDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

// 资产退库相关函数
const handleAssetReturnClick = (item, name) => {
  if (name === "state") {
    assetReturnList.approval_state = item;
  }
  returnDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const handleAssetReturnClose = (name) => {
  if (name === "state") {
    assetReturnList.approval_state = {};
  }
  returnDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const handleAssetReturnUser = () => {
  assetReturnList.show = true;
};

// 处理退库开始时间
const handleReturnStartTime = (time) => {
  assetReturnList.start_date = formatTimestamp(time, "yyyy-MM-dd");
  if (assetReturnList.start_date && assetReturnList.end_date) {
    assetReturnList.dateRange = `${assetReturnList.start_date} ~ ${assetReturnList.end_date}`;
  }
};

// 处理退库结束时间
const handleReturnEndTime = (time) => {
  assetReturnList.end_date = formatTimestamp(time, "yyyy-MM-dd");
  if (assetReturnList.start_date && assetReturnList.end_date) {
    assetReturnList.dateRange = `${assetReturnList.start_date} ~ ${assetReturnList.end_date}`;
  }
};

// 清空退库筛选条件
const handleAssetReturnClear = () => {
  assetReturnList.approval_state = {};
  assetReturnList.return_name = "";
  assetReturnList.user = {};
  assetReturnList.return_date = "";
  assetReturnList.start_date = "";
  assetReturnList.end_date = "";
  assetReturnList.dateRange = "";
  returnDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const assetReturnConfirm = (e) => {
  assetReturnList.user.text = e.value[0].text;
  assetReturnList.user.id = e.value[0].id;
  assetReturnList.show = false;
};

// 处理退库查询
const handleAssetReturnQuery = () => {
  returnDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

// 资产报修相关函数
const handleAssetWarrantyClick = (item, name) => {
  if (name === "state") {
    assetWarrantyList.repair_state = item;
  }
  warrantyDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const handleAssetWarrantyClose = (name) => {
  if (name === "state") {
    assetWarrantyList.repair_state = {};
  }
  warrantyDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const handleAssetWarrantyUser = () => {
  assetWarrantyList.show = true;
};

// 清空报修筛选条件
const handleAssetWarrantyClear = () => {
  assetWarrantyList.repair_state = {};
  assetWarrantyList.user = {};
  assetWarrantyList.repair_code = "";
  assetWarrantyList.repair_name = "";
  warrantyDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const assetWarrantyConfirm = (e) => {
  assetWarrantyList.user.text = e.value[0].text;
  assetWarrantyList.user.id = e.value[0].id;
  assetWarrantyList.show = false;
};

// 处理报修查询
const handleAssetWarrantyQuery = () => {
  warrantyDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const handleAssetRequisitionConfirm = () => {
  uDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const handleUpdate = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理报废状态点击
const handleScrappingStatusClick = (item) => {
  scrappingFilter.state = item;
  console.log(scrappingFilter.state);
  scrappingDropdownRef.value.close();
  reloadData();
};

// 清空报废状态筛选
const clearScrappingStatus = () => {
  scrappingFilter.state = {};
  scrappingDropdownRef.value.close();
  reloadData();
};

// 处理报废原因点击
const handleScrappingReasonClick = (item) => {
  scrappingFilter.reason = item;
  scrappingDropdownRef.value.close();
  reloadData();
};

// 清空报废原因筛选
const clearScrappingReason = () => {
  scrappingFilter.reason = {};
  scrappingDropdownRef.value.close();
  reloadData();
};

// 处理报废人点击
const handleScrappingPersonClick = (item) => {
  scrappingFilter.person = item;
  scrappingDropdownRef.value.close();
  reloadData();
};

// 清空报废人筛选
const clearScrappingPerson = () => {
  scrappingFilter.person = {};
  scrappingDropdownRef.value.close();
  reloadData();
};
const handleAssetChangeOrderClick = (item, name) => {
  if (name === "state") {
    assetChangeOrder.state = item;
  }
  uDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const handleAssetChangeOrderClose = (name) => {
  if (name === "state") {
    assetChangeOrder.state = {};
  }
  uDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const handleAssetChangeOrderConfirm = () => {
  uDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const handleAssetChangeOrderClear = () => {
  assetChangeOrder.state = {};
  assetChangeOrder.change_date = "";
  assetChangeOrder.start = "";
  assetChangeOrder.end = "";
  assetChangeOrder.asset_name = "";
  assetChangeOrder.change_reason = "";
  assetChangeOrder.asset_name = "";
  assetChangeOrder.change_name = "";
  uDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

const handleOrderStartTime = (e) => {
  assetChangeOrder.start = formatTimestamp(e);
};

const handleOrderEndTime = (e) => {
  assetChangeOrder.end = formatTimestamp(e);

  assetChangeOrder.change_date = `${assetChangeOrder.start}-${assetChangeOrder.end}`;
};

// 处理资产转移状态点击
const handleAssetTransferClick = (item, name) => {
  if (name === "state") {
    assetTransferList.approval_state = item;
  }
  transferDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空资产转移状态
const handleAssetTransferClose = (name) => {
  if (name === "state") {
    assetTransferList.approval_state = {};
  }
  transferDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

// 显示转移人选择器
const handleAssetTransferUser = () => {
  assetTransferList.show = true;
  assetTransferList.columns = [];
  assetTransferList.columns.push(filter.disposalUsers);
};

// 显示接收人选择器
const handleAssetTransferReceiveUser = () => {
  assetTransferList.receiveUserShow = true;
  assetTransferList.receiveUserColumns = [];
  assetTransferList.receiveUserColumns.push(filter.disposalUsers);
};

// 转移人确认
const assetTransferConfirm = (e) => {
  assetTransferList.user = e.value[0];
  assetTransferList.show = false;
};

// 接收人确认
const assetTransferReceiveUserConfirm = (e) => {
  assetTransferList.receiver_user = e.value[0];
  assetTransferList.receiveUserShow = false;
};

// 处理转移查询
const handleAssetTransferQuery = () => {
  transferDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空所有转移筛选条件
const handleAssetTransferClear = () => {
  assetTransferList.approval_state = {};
  assetTransferList.transfer_code = "";
  assetTransferList.user = {};
  assetTransferList.transfer_date = "";
  assetTransferList.transfer_name = "";
  assetTransferList.receiver_user = {};
  assetTransferList.start_date = "";
  assetTransferList.end_date = "";
  assetTransferList.dateRange = "";
  assetTransferList.receiver_location = {};
  transferDropdownRef.value.close();
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理转移开始时间
const handleTransferStartTime = (time) => {
  assetTransferList.start_date = formatTimestamp(time, "yyyy-MM-dd");
  if (assetTransferList.start_date && assetTransferList.end_date) {
    assetTransferList.dateRange = `${assetTransferList.start_date} ~ ${assetTransferList.end_date}`;
  }
};

// 处理转移结束时间
const handleTransferEndTime = (time) => {
  assetTransferList.end_date = formatTimestamp(time, "yyyy-MM-dd");
  if (assetTransferList.start_date && assetTransferList.end_date) {
    assetTransferList.dateRange = `${assetTransferList.start_date} ~ ${assetTransferList.end_date}`;
  }
};
// 显示接收位置选择器
const handleAssetTransferLocation = async () => {
    assetTransferList.locationShow = true;
};

// 确认选择接收位置
const assetTransferLocationConfirm = (e) => {
  const [location] = e.value;
  assetTransferList.receiver_location = location;
  assetTransferList.locationShow = false;
};

const cssVars = computed(() => ({
  '--padding-bottom': tabIndex.value !== 6 ? '130rpx' : '20rpx'
}))
</script>

<style lang="scss" scoped>
.asset-page {
  background-color: #f5f5f5;
  min-height: calc(100vh - var(--window-top, 0px));
  .search-bar {
    display: flex;
    align-items: center;
    gap: 20rpx;
    background: #fff;
    box-sizing: border-box;
    padding: 20rpx;
    border-bottom: 1rpx solid #f5f5f5;

    .scan-btn {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .filter-bar {
    background: #fff;
    border-bottom: 1rpx solid #f5f5f5;
    .assets-class {
      width: 100%;
      box-sizing: border-box;
      padding: 20rpx;
    }
    .filter-item {
      width: 100%;
      box-sizing: border-box;
      padding: 20rpx;
    }
    .more-container {
      padding: 20rpx;
      &-items {
        display: flex;
        flex: 1;
        margin-bottom: 15rpx;
      }
    }
  }

  .overview {
    display: flex;
    justify-content: space-between;
    font-size: 26rpx;
    color: #666;
    background: #fff;
    flex-direction: row;
    position: relative;
    z-index: 10;
    padding: 20rpx 30rpx;
  }
  :deep(.zp-view-super) {
    padding-bottom: var(--padding-bottom) !important;
  }

  .footer-btn {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20rpx 30rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  }
}
.date-range-item {
  width: 100%;
  box-sizing: border-box;
  padding: 20rpx;
  text-align: center;
  color: #2979ff;
}
.date-filter-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 70rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  position: relative;
}

.date-filter-item::after {
  content: "";
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 0;
  height: 0;
  border-left: 10rpx solid transparent;
  border-right: 10rpx solid transparent;
  border-top: 10rpx solid #c0c4cc;
}
.date-range-btn {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  height: 70rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #2979ff;
  background: #fff;
  margin: 10rpx 0;
  cursor: pointer;
}
</style>
